﻿using System;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web.Mvc;
using Pyramid.Bll;
using Pyramid.Models;

namespace Pyramid.Controllers
{
	public class ConsumeController : BaseController
	{
		private readonly ConsumeHelper _helper = new ConsumeHelper();

		public ActionResult ConsumeRecords(ConsumeRecordQueryModel model)
		{
			var crquery = _helper.Query(model, User);

			var currentPage = (model.PageNum ?? 1) - 1;
			var pageSize = model.NumPerPage ?? 20;

			var vm = new PagerModel
			{
				PageSize = pageSize,
				CurrentPageIndex = currentPage,
				TotalCount = crquery.Count()
			};
			ViewBag.Bag = vm;
			ViewBag.QueryModel = model;

			return View(crquery.OrderByDescending(x => x.Id).Skip(currentPage*pageSize).Take(pageSize).ToList());
		}

		/// <summary>
		/// 我的消费记录（顾客）
		/// </summary>
		public ActionResult MyConsumeRecords(PagerQueryModel model)
		{
			if (User.UserType != UserTypes.Customer) return NoAuthorization("此功能仅对直接客户开放！");

			var crquery = _helper.MyQuery(User.ExtInfoId);
			var currentPage = (model.PageNum ?? 1) - 1;
			var pageSize = model.NumPerPage ?? 20;

			var vm = new PagerModel
			{
				PageSize = pageSize,
				CurrentPageIndex = currentPage,
				TotalCount = crquery.Count()
			};
			ViewBag.Bag = vm;
			return View(crquery.OrderByDescending(x => x.Id).Skip(currentPage * pageSize).Take(pageSize).ToList());
		}

		public ActionResult CreateRecord()
		{
			var model = new ConsumeRecord
			{
				CreateUserId = User.UserId,
				CreateTime = DateTime.Now,
				EditTime = DateTime.Now,
				EditUserId = User.UserId
			};
			return View("EditRecord", model);
		}

		public ActionResult EditRecord(int id)
		{
			var model = Db.ConsumeRecords.Include(x => x.ConsumeItem).Include(x => x.Customer).First(x => x.Id == id);
			return View(model);
		}

		[HttpPost]
		public ActionResult EditRecord(ConsumeRecord model)
		{
			model.EditTime = DateTime.Now;
			model.EditUserId = User.UserId;

			if (model.Id == 0)
			{
				model.CreateTime = DateTime.Now;
				model.CreateUserId = User.UserId;
				Db.ConsumeRecords.Add(model);
			}
			else
			{
				Db.Entry(model).State = EntityState.Modified;
			}
			Db.SaveChanges();
			return JSuccess("操作成功", "tab_ccm_consumerecord");
		}

		public ActionResult DeleteRecord(int id)
		{
			var model = new ConsumeRecord {Id = id};
			Db.Entry(model).State = EntityState.Deleted;
			Db.SaveChanges();
			return JSuccess("删除成功", "tab_ccm_consumerecord");
		}
	}
}